package com.yxq.mdt.app.modules.socialcontact.ui.activity;

import android.media.AudioManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ToastUtils;
import com.hyphenate.chat.EMCallStateChangeListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.EMNoActiveCallException;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.media.EMCallSurfaceView;
import com.hyphenate.util.EMLog;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.glide.GlideHelper;
import com.yxq.mdt.app.modules.personal.bean.MyPersonalBean;
import com.yxq.mdt.app.modules.personal.model.UserModel;
import com.yxq.mdt.app.modules.socialcontact.model.LiveModel;
import com.yxq.mdt.app.modules.socialcontact.presenter.ILiveContract;
import com.yxq.mdt.app.modules.socialcontact.presenter.LivePresenter;
import com.yxq.mdt.app.modules.withdraw.bean.WithDrawResultBean;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.PhoneStateManager;
import com.yxq.mdt.app.utils.StringUtils;
import com.yxq.mdt.app.widgets.CircleImageView;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 视频接受方
 */
public class VideoTakeChatActivity extends CallActivity<LivePresenter> implements ILiveContract.View {
    protected EMCallStateChangeListener callStateListener; //通话状态监听器
    @BindView(R.id.local_surface_image)
    CircleImageView localSurfaceImage;
    @BindView(R.id.btn_answer)
    ImageView btnAnswer;
    @BindView(R.id.btn_refuse)
    ImageView btnRefuse;
    @BindView(R.id.tv_one_status)
    TextView tvOneStatus;
    @BindView(R.id.opposite_two_surface)
    EMCallSurfaceView oppositeTwoSurface;
    @BindView(R.id.local_two_surface)
    EMCallSurfaceView localTwoSurface;
    @BindView(R.id.time_two_tv)
    TextView timeTwoTv;
    @BindView(R.id.btn_present_two)
    ImageView btnPresentTwo;
    @BindView(R.id.btn_two_hangup)
    ImageView btnTwoHangup;
    @BindView(R.id.btn_switch_two)
    ImageView btnSwitchTwo;
    @BindView(R.id.tv_two_status)
    TextView tvTwoStatus;
    @BindView(R.id.open_chat_lint_two)
    RelativeLayout openChatLintTwo;
    @BindView(R.id.open_chat_lint_one)
    RelativeLayout openChatLintOne;
    @BindView(R.id.take_video_tv_nick_name)
    TextView takeVideoTvNickName;
    @BindView(R.id.layout_alert_layout)
    LinearLayout layoutAlertLayout;
    // 视频通话画面显示控件，这里在新版中使用同一类型的控件，方便本地和远端视图切换
    private int surfaceState = -1;
    private String from;
    CountDownTimer countDownTimer;
    String userId;
    private boolean isMuteState;
    private boolean isHandsfreeState;

    @Override
    public int getLayoutId() {
        setStatusBarDarkFont(false);
        setEnableImmersion(true);
        setStatusBarColor(R.color.black);
        return R.layout.activity_take_video_chat;
    }
    @Override
    public void onBackPressed() {

    }
    @Override
    public void initView() {
        super.initView();
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

        localTwoSurface.setZOrderMediaOverlay(true);
        localTwoSurface.setZOrderOnTop(true);
        //设置Surface
        EMClient.getInstance().callManager().setSurfaceView(localTwoSurface, oppositeTwoSurface);
        from = getIntent().getStringExtra("from");
        takeVideoTvNickName.setText(from + "");
        new Handler().postDelayed(() -> addCallStateListener(), 500);
        btnPresentTwo.setOnClickListener(view -> ToastUtils.showShort("该功能正在开发中"));
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new LivePresenter(this, new LiveModel());
        userId = from.replaceAll("yxq", "");
        UserModel.getGaUserExtVoById(userId, new ApiModel.CommonCallback<MyPersonalBean>() {
            @Override
            public void onSuccess(MyPersonalBean myPersonalBean) {
                if (myPersonalBean != null) {
                    if (myPersonalBean.getGsName() != null) {
                        takeVideoTvNickName.setText(myPersonalBean.getGsName());
                    }
                    GlideHelper.load(mActivity, myPersonalBean.getHeadimg(), localSurfaceImage);
                }
            }

            @Override
            public void onError(String errMsg) {

            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    break;
                case 2:
                    findViewById(R.id.open_chat_lint_one).setVisibility(View.GONE);
                    findViewById(R.id.open_chat_lint_two).setVisibility(View.VISIBLE);
//                    openSpeakerOn();
                    startTimer();
                    // Start to watch the phone call state.
                    PhoneStateManager.get(VideoTakeChatActivity.this).addStateCallback(phoneStateCallback);
                    break;
                case 3:
                    PhoneStateManager.get(VideoTakeChatActivity.this).removeStateCallback(phoneStateCallback);
                    removeCallStateListener();
                    finish();
                    break;
            }
        }
    };

    void removeCallStateListener() {
        EMClient.getInstance().callManager().removeCallStateChangeListener(callStateListener);
    }

    int time = 0;

    private void startTimer() {
        //调用计费接口
        countDownTimer = new CountDownTimer(Long.MAX_VALUE, 1000) {
            @Override
            public void onTick(long l) {
                time++;
                View view = findViewById(R.id.layout_alert_layout);
                if (time >= 5 && view.getVisibility() == View.VISIBLE) {
                    view.setVisibility(View.GONE);
                }
                TextView tvTime = findViewById(R.id.time_two_tv);
                tvTime.setText(StringUtils.formatTime(time));
            }

            @Override
            public void onFinish() {

            }
        };
        countDownTimer.start();
    }

    private void finishChat() {
//        mPresenter.addOrUpdateVideo(from, 2);
    }

    /**
     * 接听通话
     */
    public void answerCall() {
        try {
            EMClient.getInstance().callManager().answerCall();
        } catch (EMNoActiveCallException e) {
            e.printStackTrace();
        }

    }

    /**
     * 挂断
     */
    public void newEndCall() {
        try {
            EMClient.getInstance().callManager().endCall();
        } catch (EMNoActiveCallException e) {
            e.printStackTrace();
        } finally {
            finish();
        }
    }

    /**
     * 拒绝接听
     */
    public void refuseCall() {
        try {
            EMClient.getInstance().callManager().rejectCall();
            finish();
        } catch (EMNoActiveCallException e) {
            e.printStackTrace();
            finish();
        }
    }

    /**
     * 转换摄像头
     */
    public void switchCamera() {
        EMClient.getInstance().callManager().switchCamera();
    }

    @OnClick({R.id.btn_answer, R.id.btn_refuse, R.id.btn_two_hangup, R.id.btn_switch_two})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_answer:
                refuseCall();
                break;
            case R.id.btn_two_hangup:
                newEndCall();
                break;
            case R.id.btn_refuse:
//                openSpeakerOn();
                if (ringtone != null)
                    ringtone.stop();
                answerCall();
                break;
            case R.id.btn_switch_two:
                switchCamera();
                break;
//            case R.id.iv_mute:
//                //静音
//                if (isMuteState) {
//                    ImageView muteImage = findViewById(R.id.iv_mute);
//                    muteImage.setImageResource(R.mipmap.em_icon_mute_normal);
//                    try {
//                        EMClient.getInstance().callManager().resumeVoiceTransfer();
//                    } catch (HyphenateException e) {
//                        e.printStackTrace();
//                    }
//                    isMuteState = false;
//                } else {
//                    ImageView muteImage = findViewById(R.id.iv_mute);
//                    muteImage.setImageResource(R.mipmap.em_icon_mute_on);
//                    try {
//                        EMClient.getInstance().callManager().pauseVoiceTransfer();
//                    } catch (HyphenateException e) {
//                        e.printStackTrace();
//                    }
//                    isMuteState = true;
//                }
//                break;
//            case R.id.iv_handsfree:
//                //扬声器
//                if (isHandsfreeState) {
//                    ImageView handsFreeImage = findViewById(R.id.iv_handsfree);
//                    handsFreeImage.setImageResource(R.mipmap.em_icon_speaker_normal);
//                    closeSpeakerOn();
//                    isHandsfreeState = false;
//                } else {
//                    ImageView handsFreeImage = findViewById(R.id.iv_handsfree);
//                    handsFreeImage.setImageResource(R.mipmap.em_icon_speaker_on);
//                    openSpeakerOn();
//                    isHandsfreeState = true;
//                }
//                break;
        }
    }

    private void addCallStateListener() {
        callStateListener = new EMCallStateChangeListener() {
            @Override
            public void onCallStateChanged(CallState callState, CallError callError) {
                switch (callState) {
                    case CONNECTING: // 正在连接对方
                        break;
                    case CONNECTED: // 双方已经建立连接
                        mHandler.sendEmptyMessage(1);
                        break;
                    case ACCEPTED: // 电话接通成功
                        mHandler.sendEmptyMessage(2);
                        break;
                    case DISCONNECTED: // 电话断了
                        mHandler.sendEmptyMessage(3);
                        break;
                    case NETWORK_UNSTABLE: //网络不稳定
                        if (callError == CallError.ERROR_NO_DATA) {
                            //无通话数据
                        } else {
                        }
                        break;
                    case NETWORK_NORMAL: //网络恢复正常
                        break;
                    default:
                        break;
                }

            }
        };

        EMClient.getInstance().callManager().addCallStateChangeListener(callStateListener);

        //声音提示
        Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
        audioManager.setMode(AudioManager.MODE_RINGTONE);
        audioManager.setSpeakerphoneOn(true);
        ringtone = RingtoneManager.getRingtone(this, ringUri);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            ringtone.setLooping(true);
        }
        ringtone.play();
    }

    @Override
    protected void onDestroy() {
        finishChat();
        newEndCall();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        super.onDestroy();
    }
    PhoneStateManager.PhoneStateCallback phoneStateCallback = new PhoneStateManager.PhoneStateCallback() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:   // 电话响铃
                    break;
                case TelephonyManager.CALL_STATE_IDLE:      // 电话挂断
                    // resume current voice conference.
                    if (isMuteState) {
                        try {
                            EMClient.getInstance().callManager().resumeVoiceTransfer();
                        } catch (HyphenateException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:   // 来电接通 或者 去电，去电接通  但是没法区分
                    // pause current voice conference.
                    if (!isMuteState) {
                        try {
                            EMClient.getInstance().callManager().pauseVoiceTransfer();
                        } catch (HyphenateException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
            }
        }
    };
    @Override
    public void onLoadLiveSuccess(int status, String result) {

    }

    @Override
    public void onLoadLiveFailed(String err) {

    }

    @Override
    public void onCommentSuccess(WithDrawResultBean result) {

    }

    @Override
    public void onCommentFailed(String err) {

    }
}
